/** 密钥**/
const router = require("koa-router")();
const moment = require("moment");
const _ = require("lodash");

/**
 * api {get} /home/app/auth/auth 密钥列表
 *
 *
 */
router.get("/auth", async (ctx, nex) => {
  const user = ctx.user;
  const baas = ctx.baas;

  const auth = await BaaS.Models.auth
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      qb.orderBy("id", "desc");
    })
    .fetchAll({
      withRelated: []
    });

  ctx.success(auth, "秘钥列表");
});
/**
 * api {get} /home/app/auth/info/auth 密钥额外信息
 *
 *
 */
router.get("/info/auth", async (ctx, nex) => {
  const user = ctx.user;
  const baas = ctx.baas;

  const data = {
    time: [
      {
        name: "天",
        value: "days"
      },
      {
        name: "小时",
        value: "hour"
      }
    ]
  };

  ctx.success(data, "秘钥额外信息");
});
/**
 * api {get} /home/app/auth/auth/:id 获取单个密钥信息
 *
 * apiParam {Number} id
 *
 */
router.get("/auth/:id", async (ctx, nex) => {
  const baas = ctx.baas;
  const { id } = ctx.params;

  const auth = await BaaS.Models.auth
    .query(qb => {
      qb.where("id", "=", id);
      qb.where("baas_id", "=", baas.id);
    })
    .fetch();

  ctx.success(auth, "单个秘钥信息");
});
/**
 * api {post} /home/app/auth/add/auth 新增修改密钥
 * 
 * apiParam {
	id:1,
	name:'Authorization',
	secret:'shared-secret',
	expires:'7 days'
 } 
 * 
 */
router.post("/add/auth", async (ctx, nex) => {
  const baas = ctx.baas;
  const { id, name, secret, expires } = ctx.post;

  if (_.isEmpty(_.trim(name))) {
    ctx.error("", "名称不能为空");
    return;
  }

  if (_.isEmpty(_.trim(secret))) {
    ctx.error("", "密钥不能为空");
    return;
  }

  const auth = await BaaS.Models.auth
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      qb.where("name", "=", name);
    })
    .fetch();
  if (auth && auth.id != id) {
    ctx.error("", "密钥名称已存在");
    return;
  }

  const result = await BaaS.Models.auth
    .forge({
      id: id,
      baas_id: baas.id,
      name: name,
      secret: secret,
      expires: expires
    })
    .save();
  // 删除redis缓存
  await BaaS.redis.delAll(
    `baas:*:appid:${baas.appid}:appkey:${baas.appkey}:class:*`
  );

  ctx.success(result, "操作成功");
});
/**
 * api {get} /home/app/auth/del/auth/:id 删除密钥
 *
 * apiParam {Number} id 密钥id
 *
 */
router.get("/del/auth/:id", async (ctx, nex) => {
  const baas = ctx.baas;
  const { id } = ctx.params;

  const auth = await BaaS.Models.auth
    .query(qb => {
      qb.where("id", "=", id);
      qb.where("baas_id", "=", baas.id);
    })
    .fetch();
  if (!auth) {
    ctx.error("", "参数错误");
    return;
  }

  const result = await BaaS.Models.auth
    .forge({
      id: id
    })
    .destroy();
  // 删除redis缓存
  await BaaS.redis.delAll(
    `baas:*:appid:${baas.appid}:appkey:${baas.appkey}:class:*`
  );

  ctx.success(result, "操作成功");
});

module.exports = router;
